<?php

namespace app\admin\controller;
//use think\Controller;
use My\MyClass;
use think\Db;
use think\Request;

class permission extends MyClass
{
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {
        $row = Db::table('permission')->select();

        return view('admin@permission/index', [
            'data' => $row,
        ]);
    }

    /**
     * 显示创建资源表单页.
     *
     * @return \think\Response
     */
    public function pmadd()
    {
        return view('admin@permission/perm');
    }

    /**
     * 保存新建的资源
     *
     * @param \think\Request $request
     * @return \think\Response
     */
    public function pmdoadd(Request $request)
    {
        $result = $request->post();
        $name = $result['permission'];
        $mysql = Db::table('permission')->field('permission')->select();

        foreach ($mysql as $v) {
            if ($name == $v['permission']) {
                return $this->error('权限名重复 请重试!');
            }
        }


        $row = Db::table('permission')->insert($result);

        if ($row > 0) {
            return $this->success('添加成功!', '/Users/permission');
        } else {
            return $this->error('添加失败,请重试!');
        }
    }


    public function peradd($id)
    {
        //查看所有权限名
        $row = Db::table('permission')->field('permission,id')->select();
//        halt($row);

        //查看当前用户拥有的角色
        $result = Db::field(['p.id','p.permission' => 'pn'])
            ->table(['permission' => 'p', 'jiaose' => 'j', 'jiaose_q' => 'jq'])
            ->where('p.id=jq.qid and j.id=jq.jid and jid='.$id)
            ->order('p.id desc')
            ->select();

        for($i=0;$i<count($result);$i++){
            $arr['pn'][]=$result[$i]['pn'];
            $arr1 = $arr['pn'];
        }

        return view('admin@/jiaose/fenpei',[
            'data'=>$row,
            'quanxian'=>$arr1,
            'id'=>$id
            ]);
    }

    public function addper(Request $request,$id)
    {
        $p = $request->post();

        if ($p == null){
            return $this->error('您没有添加任何权限!');
        }


//        halt($p);
        $abc = [];

        foreach ($p as $k=>$v){

            foreach ($v as $val){

                $abc[] = ['jid'=>$id,'qid'=>$val];
            }
        }

        //添加之前先删除
        Db::table('jiaose_q')->where('jid='.$id)->delete();
        for ($i=0;$i<count($abc);$i++){
            $row = Db::table('jiaose_q')->insert($abc[$i]);
        }
        if ($row >0){
            return $this->success('添加成功!','/users/jiaose');
        }else{
            return $this->error('添加失败,请重试!');
        }
    }

    /**
     * 显示编辑资源表单页.
     *
     * @param int $id
     * @return \think\Response
     */



}
